﻿using PunchCard.Service;
using PunchCard.View;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using MSExcel = Microsoft.Office.Interop.Excel;

namespace PunchCard.Model
{
    class ModelMainWindow : INotifyPropertyChanged
    {
        #region MVVMM
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        public ModelMainWindow()
        {
            OA_Thread_Init();
            AddModel("", "", "欢迎使用OA", "签卡!", "");
            AddModel("", "", "共有三种模式", "数据源类型不同", "");
            AddModel("", "", "1、自己上OA", "导出考勤查询", "");
            AddModel("", "", "2、等人事发", "邮件考勤异常", "");
            AddModel("", "", "3、自动生成当月", "签卡导入表", "(仅工作日)");
            AddModel("", "将工号和原因", "填写好!", "", "");
            AddModel("", "可将Excel拖入", "即可!", "", "");
        }

        public BackgroundWorker m_OAThread = null;
        private void OA_Thread_Init()
        {
            m_OAThread = new BackgroundWorker();
            m_OAThread.DoWork += OA_LookUpClick;
            m_OAThread.WorkerSupportsCancellation = true; //允许取消
        }

        public void Model2(ref FileParam param)
        {
            m_LExcel.Clear();
            List<string> LTime = new List<string>() { "8:30", "12:00", "13:30", "18:00" };
            nNum = 0;
            if (m_ListWorker.Count != 0)
            {
                string strFileFolder = AppDomain.CurrentDomain.BaseDirectory + "考勤导入文件\\";
                if (!Directory.Exists(strFileFolder))
                    Directory.CreateDirectory(strFileFolder);
                m_LExcel.Clear();
                foreach (var item in m_ListWorker)
                {
                    ObservableCollection<CsListINF> Litem_Pro = new ObservableCollection<CsListINF>();
                    foreach (var it in m_ListMonth)
                        for (int i = 0; i < 4; i++)
                        {
                            CsListINF listINF = new CsListINF()
                            {
                                strID = (Litem_Pro.Count + 1).ToString(),
                                strName = item.FileName + "_" + item.FileID,
                                strDate = it,
                                strTime = LTime[i],
                                strType = "正常签卡",
                                strReason = item.Reason
                            };
                            Litem_Pro.Add(listINF);
                            nNum++;
                        }

                    foreach (var itemPro in Litem_Pro)
                        m_LExcel.Add(itemPro);
                    string strWriteFileFolder = strFileFolder + item.FileName + "_" + item.FileID + ".xls";// Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";
                    CsExcelWrite.ExportLists(strWriteFileFolder, Litem_Pro);
                }
            }
            else
            {
                foreach (var item in m_ListMonth)
                    for (int i = 0; i < 4; i++)
                    {
                        CsListINF listINF = new CsListINF()
                        {
                            strID = (m_LExcel.Count + 1).ToString(),
                            strName = m_strName + "_" + m_strID,
                            strDate = item,
                            strTime = LTime[i],
                            strType = "正常签卡",
                            strReason = param.Reason
                        };
                        m_LExcel.Add(listINF);
                    }
            }
        }

        public void LookupLists(string strFilePath, string strFileID, string strReason)
        {
            FileParam param = new FileParam()
            {
                FilePath = strFilePath,
                FileID = strFileID,
                Reason = strReason,
            };
            IsShow = "Visible";
            m_OAThread.RunWorkerAsync(param);
        }

        private void OA_LookUpClick(object sender, DoWorkEventArgs e)
        {
            try
            {
                FileParam param = (FileParam)e.Argument;
                ObservableCollection<CsListINF> Litem = new ObservableCollection<CsListINF>();
                if (m_nModel == 0)
                {
                    CsExcelRead.ex_Read_2(ref Litem, ref param);
                }
                else if (m_nModel == 1)
                {
                    nNum = 0;
                    if (m_ListWorker.Count != 0)
                    {
                        string strFileFolder = AppDomain.CurrentDomain.BaseDirectory + "考勤导入文件\\";

                        if (!Directory.Exists(strFileFolder))
                            Directory.CreateDirectory(strFileFolder);

                        MSExcel.Application excelApp = new MSExcel.Application();
                        MSExcel._Workbook workbook = excelApp.Workbooks.Add(param.FilePath);
                        MSExcel.Worksheet worksheet = (MSExcel.Worksheet)workbook.Worksheets.get_Item(1);//读取第一张表，以顺序
                        System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate ()
                        { m_LExcel.Clear(); });
                        string strUnDeal = string.Empty;
                        string strName1 = string.Empty;
                        string strName2 = string.Empty;
                        foreach (var item in m_ListWorker)
                        {
                            ObservableCollection<CsListINF> Litem_Pro = new ObservableCollection<CsListINF>();
                            if (!CsExcelRead.ex_Read_1_Pro(ref worksheet, ref Litem_Pro, item))
                                break;
                            System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate ()
                            {
                                foreach (var itemPro in Litem_Pro)
                                {
                                    m_LExcel.Add(itemPro);
                                    strName1 = itemPro.strName;
                                    strUnDeal += strName1 != strName2 ? strName1 + "\r\n" : "";
                                    strName2 = strName1;
                                }
                                nNum++;
                            });
                            System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
                            {
                                string strWriteFileFolder = strFileFolder + item.FileName + "_" + item.FileID + ".xls";
                                CsExcelWrite.ExportLists(strWriteFileFolder, Litem_Pro);
                            });
                        }
                        workbook.Close();//关闭文档
                        excelApp.Quit();//关闭excel应用程序
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);//释放excel进程
                        excelApp = null;
                        IsShow = "Hidden";
                        MessageBox.Show("所有导出表在软件根目录中，以下人员存在考勤异常：\r\n" + strUnDeal,
                            "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    else
                        CsExcelRead.ex_Read_1(ref Litem, ref param);
                }
                if (Litem.Count == 0)
                {
                    MessageBox.Show("未匹配到相关信息");
                    return;
                }
                System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
                {
                    m_LExcel.Clear();
                    foreach (var item in Litem)
                        m_LExcel.Add(item);
                });

                IsShow = "Hidden";

                if (CsINI.ReadRealValue("card.ini", "是否开启自动化", "是[1]否[0]", "0") == "1")
                {
                    System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate ()
                    {
                        string strSrcFileFolder = param.FilePath.Substring(0, param.FilePath.LastIndexOf("\\"));
                        string strWriteFileFolder = strSrcFileFolder + "\\" + param.FileName + "_" + param.FileID + ".xls";// Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";
                        if (CsExcelWrite.ExportLists(strWriteFileFolder, Litem))
                            MessageBox.Show("成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        ((MainWindow)System.Windows.Application.Current.MainWindow).Exit();
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        //===============================================================================================================

        private void AddModel(string strId, string strName, string strDate, string strTime, string strReason)
        {
            CsListINF listINF = new CsListINF()
            {
                strID = (m_LExcel.Count + 1).ToString(),
                strName = strName,
                strDate = strDate,
                strTime = strTime,
                strType = "正常签卡",
                strReason = strReason
            };
            m_LExcel.Add(listINF);
        }

        //===============================================================================================================

        public int GetWorkingDays(int year, int month)
        {
            m_ListMonth.Clear();
            //获取该月总计天数
            int days = DateTime.DaysInMonth(year, month);
            //休息天数
            int weekDays = 0;
            for (int i = 0; i < days; i++)
            {
                //每逢周六/周日 休息天数增加一天
                DateTime dateTime = new DateTime(year, month, i + 1);//初始化一个日期
                switch (dateTime.DayOfWeek)
                {
                    case DayOfWeek.Sunday:
                    case DayOfWeek.Saturday:
                        if (IsWorkDay(dateTime))
                            m_ListMonth.Add(dateTime.ToString("yyyy-MM-dd"));
                        else
                            weekDays++;
                        break;
                    default:
                        if (!IsRestDay(dateTime))
                            m_ListMonth.Add(dateTime.ToString("yyyy-MM-dd"));
                        break;
                }
                dateTime.AddDays(1);
            }
            //工作日等于当月总天数减去非工作日
            int workDays = days - weekDays;
            return workDays;
        }

        private bool IsRestDay(DateTime time)//工作日是否放假
        {
            var day = time.ToString("MM-dd");
            List<string> LDate = new List<string>()//2023年
            {
                "01-02", "01-23", "01-24", "01-25", "01-26", "01-27",
                "04-05",
                "05-01", "05-02", "05-03",
                "06-22", "06-23",
                "09-29",
                "10-02", "10-03", "10-04", "10-05","10-06",
            };
            foreach (var item in LDate)
                if (day == item)
                    return true;
            return false;
        }

        private bool IsWorkDay(DateTime time)//周末是否上班
        {
            var day = time.ToString("MM-dd");
            List<string> LDate = new List<string>()
            {
                "01-28", "01-29",
                "04-23",
                "05-06",
                "06-25",
                "10-07","10-08",
            };
            foreach (var item in LDate)
                if (day == item)
                    return true;
            return false;
        }

        //===============================================================================================================

        public int m_nYear = int.Parse(DateTime.Now.Year.ToString());
        public int m_nMonth = int.Parse(DateTime.Now.Month.ToString()) == 1 ? 1 : int.Parse(DateTime.Now.Month.ToString()) - 1;
        public string m_strID = "002008";
        public string m_strName = "大族激光";
        public int m_nModel = 1;//0：个人自查模式 1：人事异常模式 2：常驻出差人员
        public bool m_bBatchModel = false;
        public List<string> m_ListMonth = new List<string>();//每月工作日

        //===============================================================================================================

        public List<FileParam> m_ListWorker = new List<FileParam>();//批量人员
        public bool ex_Read_3(string strFilePath)
        {

            bool bIsStart = true;
            m_ListWorker.Clear();
            MSExcel.Application excelApp = new MSExcel.Application();
            MSExcel._Workbook workbook = excelApp.Workbooks.Add(strFilePath);
            MSExcel.Worksheet worksheet = (MSExcel.Worksheet)workbook.Worksheets.get_Item(1);//读取第一张表，以顺序
                                                                                             //MSExcel.Worksheet worksheet = (MSExcel.Worksheet)workbook.Worksheets["sheet"];//读取第一张表，以表名
            {//处理表内内容

                int nRowCnt = worksheet.UsedRange.CurrentRegion.Rows.Count;//累计行数
                if (nRowCnt == 1)
                {
                    MessageBox.Show("批量导入名单未填写信息，请填写", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    bIsStart = false;
                }
                string strCurrent = CsExcelRead.ex_ReadContext(ref worksheet, 2, 7);//该单元格文本
                for (int i = 2; i < nRowCnt + 1; i++)//从第二行开始
                {
                    FileParam param = new FileParam()
                    {
                        FileName = CsExcelRead.ex_ReadContext(ref worksheet, i, 1),
                        FileID = CsExcelRead.ex_ReadContext(ref worksheet, i, 2),
                        Reason = CsExcelRead.ex_ReadContext(ref worksheet, i, 3),

                    };
                    m_ListWorker.Add(param);
                }
            }
            nCnt = m_ListWorker.Count;
            workbook.Close();//关闭文档
            excelApp.Quit();//关闭excel应用程序
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);//释放excel进程
            excelApp = null;
            return bIsStart;
        }

        //===============================================================================================================

        private string _FilePath = string.Empty;
        public string strFilePath
        {
            get { return _FilePath; }
            set { if (_FilePath != value) { _FilePath = value; RaisePropertyChanged(""); } }
        }

        private string _IsShow = "Hidden";
        public string IsShow
        {
            get { return _IsShow; }
            set { if (_IsShow != value) { _IsShow = value; RaisePropertyChanged(""); } }
        }

        private int _nCnt = 0;
        public int nCnt
        {
            get { return _nCnt; }
            set { if (_nCnt != value) { _nCnt = value; RaisePropertyChanged(""); } }
        }
        private int _nNum = 0;
        public int nNum
        {
            get { return _nNum; }
            set { if (_nNum != value) { _nNum = value; RaisePropertyChanged(""); } }
        }

        private ObservableCollection<CsListINF> _m_LExcel = new ObservableCollection<CsListINF>();
        public ObservableCollection<CsListINF> m_LExcel
        {
            get { return _m_LExcel; }
            set { if (_m_LExcel != value) { _m_LExcel = value; RaisePropertyChanged(""); } }
        }

        public struct FileParam
        {
            public string FilePath;
            public string FileID;
            public string FileName;
            public string Reason;
        }
    }

    public class CsListINF
    {
        public string strDate { get; set; }
        public string strID { get; set; }
        public string strName { get; set; }
        public string strReason { get; set; }
        public string strTime { get; set; }
        public string strType { get; set; }
    }
}
